using System;

namespace Mbs.Messaging.Imp
{
    [Serializable]
    abstract class AsyncInvoker : MarshalByRefObject, IDelegateInvoker
    {
        protected AsyncInvoker()
        {
        }

        protected abstract void Invoke(Delegate handler, params object[] args);

        protected abstract void AsyncInvoke(Delegate handler, params object[] args);

        public virtual void Invoke<TMessage>(PreFilterHandler<TMessage>[] filters, PreFilterEventArgs<TMessage> e)
        {
            if (filters == null || filters.Length < 1)
                return;

            foreach(var item in filters)
            {
                Invoke(item, e.Sender, e);
                if (e.Canceled)
                    return;
            }

           
        }

        protected virtual void Invoke<TMessage>(FilterHandler<TMessage>[] filters, FilterEventArgs<TMessage> e)
        {
            for (int i = 0; i < filters.Length; i++)
            {
                Invoke(filters[i], e.Sender, e);
                if (e.Ignored)
                    return;
            }
        }


        public virtual void Invoke<TMessage>(FilterHandler<TMessage>[] filters, ObserverHandler<TMessage> handler, FilterEventArgs<TMessage> e)
        {
            if (filters != null && filters.Length > 0)
            {
                e.Receiver = handler.Target;

                Invoke<TMessage>(filters, e);
                if (!e.Ignored)
                    AsyncInvoke(handler, e.Sender, e.Message);
            }
            else
                AsyncInvoke(handler, e.Sender, e.Message);
        }

        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}
